package com.zhu.salesmanagement;

import java.io.File;
import java.util.ArrayList;

import com.zhu.location.R;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.Log;
import com.zhu.salesmanagement.models.AddedStoreItemInfo;
import com.zhu.salesmanagement.provider.SalesSettings;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AddedStoreListActivity extends Activity implements View.OnClickListener{

	private final static int STORES_LIST_QUERY_TOKEN = 1000;
	private final static int STORES_LIST_DELETE_TOKEN = 2000;

	private static final int UPDATECONTENT = 0;

	LinearLayout mContentLayout = null;
	private ArrayList<CheckBox> mBoxList = null;
	private TextView mTitleView = null;
	private TextView mNoneView = null;
	private StoresListQueryHandler mStoresListQueryHandler = null;
	private ArrayList<AddedStoreItemInfo> lists = new ArrayList<AddedStoreItemInfo>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_addedstorelist);

        setupView();
        initData();
    }

    private void setupView(){
    	mContentLayout = (LinearLayout)findViewById(R.id.remindlist_content);
    	findViewById(R.id.remindlist_bottom_back).setOnClickListener(this);
    	findViewById(R.id.remindlist_back).setOnClickListener(this);
    	findViewById(R.id.remindlist_delete).setOnClickListener(this);
    	findViewById(R.id.addedstoreligs_addstore).setOnClickListener(this);
    	
    	mTitleView = (TextView)findViewById(R.id.addedstorelist_title);
    	mNoneView = (TextView)findViewById(R.id.none_text);
    }

    private void initData(){
    	mTitleView.setText(R.string.addedstorelist);
    	mBoxList = new ArrayList<CheckBox>();
    	mStoresListQueryHandler = new StoresListQueryHandler(getContentResolver());
    	updateContent();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v != null){
        	switch(v.getId()){
        		case R.id.remindlist_bottom_back:
        		case R.id.remindlist_back:
        			finish();
        			break;
        		case R.id.remindlist_delete:
        			deleteItems();
        			break;
        		case R.id.reminditem_row:
        			gotoContentActivity((AddedStoreItemInfo)v.getTag());
        			break;
        		case R.id.addedstoreligs_addstore:
        		    gotoContentActivity();
        		    break;
        	}
        }
    }

    private void updateContent(){
    	startStoresListAsyncQuery();
    }

    private View getRowView(AddedStoreItemInfo info){
    	View row = LayoutInflater.from(this).inflate(R.layout.remindlist_item, null);
    	View rowView = row.findViewById(R.id.reminditem_row);
    	rowView.setOnClickListener(this);
    	rowView.setTag(info);
    	CheckBox box = (CheckBox)(row.findViewById(R.id.reminditem_checkbox));
    	mBoxList.add(box);
    	box.setTag(info);
    	TextView title = (TextView)(row.findViewById(R.id.reminditem_title));
    	title.setText(info.mName);
    	return row;
    }

    private void deleteItems(){
    	int deleteCount = 0;
    	CheckBox box = null;
    	String where = "";
    	for(int i = 0; i < mBoxList.size(); i++){
    		if(mBoxList.get(i).isChecked()){
    			deleteCount++;
    			box = mBoxList.get(i);
    			AddedStoreItemInfo info = (AddedStoreItemInfo)box.getTag();
    			if(where.length() == 0){
    				where += SalesSettings.MyAddStoresColumns._ID + " = " + info.id;
    			}else{
    				where += " or " + SalesSettings.MyAddStoresColumns._ID + " = " + info.id;
    			}
    		}
    	}
    	if(deleteCount == 0){
    		Actions.toastShort(this, getResources().getString(R.string.seclectdelete));
    	}else{
    		getContentResolver().delete(SalesSettings.MyAddStoresColumns.CONTENT_URI, where, null);
    		Actions.toastShort(this, getResources().getString(R.string.delete_success));
    	}
    	updateContent();
    }

    private void gotoContentActivity(AddedStoreItemInfo info) {
        Intent intent = new Intent(this, AddStoreActivity.class);
        Bundle bundle = new Bundle();  
        bundle.putParcelable("info", info); 
        intent.putExtras(bundle);
        startActivityForResult(intent, UPDATECONTENT);
    }

    private void gotoContentActivity() {
        Intent intent = new Intent(this, AddStoreActivity.class);
        startActivityForResult(intent, UPDATECONTENT);
    }

    private void startStoresListAsyncQuery() {
        try {
        	mStoresListQueryHandler.startQuery(STORES_LIST_QUERY_TOKEN, null,
                    SalesSettings.MyAddStoresColumns.CONTENT_URI, null, null, null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    private final class StoresListQueryHandler extends AsyncQueryHandler {

        public StoresListQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case STORES_LIST_QUERY_TOKEN:
                	updateListData(cursor);
                    break;
                default:
                    Log.e("onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case STORES_LIST_DELETE_TOKEN:
                    break;
                default:
                    Log.e("onDeleteComplete called with unknown token " + token);
            }
        }
    }

    private void updateListData(Cursor cursor) {
    	if(lists != null){
    		lists.clear();
    	}
        try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns._ID);
            final int nameIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.NAME);
            final int addressIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.ADDRESS);
            final int mobileIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.MOBILE);
            final int contactIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.CONTACT);
            final int typeIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.TYPE);
            final int latIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.LAT);
            final int lngIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.LNG);
            while (cursor.moveToNext()) {
            	AddedStoreItemInfo info = new AddedStoreItemInfo();
            	info.id = cursor.getLong(idIndex);
            	info.mName = cursor.getString(nameIndex);
            	info.mAddress = cursor.getString(addressIndex);
            	info.mMobile = cursor.getString(mobileIndex);
            	info.mContact = cursor.getString(contactIndex);
            	info.mType = cursor.getString(typeIndex);
            	if(Actions.DEBUG){
            		Log.e(cursor.getString(latIndex)+"," + cursor.getString(lngIndex));
            	}
            	lists.add(info);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("updateListData error");
        } finally {
            cursor.close();
        }

        updateBodyView();
    }

    private void updateBodyView(){
    	mContentLayout.removeAllViews();
    	mBoxList.clear();
    	if(lists.size() > 0){
    		mNoneView.setVisibility(View.GONE);
    		for(int i = 0; i < lists.size(); i++){
        		mContentLayout.addView(getRowView(lists.get(i)));
        	}
    	}else{
        	mNoneView.setVisibility(View.VISIBLE);
    	}
    	
    }

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
			case UPDATECONTENT:
				updateContent();
				break;
		}
	}
}
